package com.alibaba.dongbao.utils;

import com.alibaba.dongbao.base.result.Result;
import com.alibaba.dongbao.utils.encrypt.MD5Util;
import com.alibaba.dongbao.utils.encrypt.SHA256Util;
import com.sun.prism.impl.shape.ShapeUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author: Mr.ZJW
 * @Date: 2022-05-05 11:36
 * @Description: 生产签名工具类
 */
public class SignUtil {

    private static String secret = "e10adc3949ba59abbe56e057f20f883f";

    /**
     * @param [map]
     * @Author: Mr.ZJW
     * @Description: 根据Map生成签名
     * @Date: 2022/5/5 11:38
     **/
    public static String generatorSign(Map<String, Object> map) {
        map.remove("sign");
        //排序
        Map<String, Object> stringObjectMap = MapSortUtil.sortMapByKey(map);
        //转格式
        Set<Map.Entry<String, Object>> entries = stringObjectMap.entrySet();
        //存放StringBuilder
        StringBuilder sb = new StringBuilder();
        //遍历
        for (Map.Entry<String, Object> entry : entries) {
            sb.append(entry.getKey() + ":" + entry.getValue()).append("&");
        }
        //组装secret
        sb.append("secret").append(secret);
        //生产签名
        return SHA256Util.getSHA256String(sb.toString());
    }

    /**
     * @Author: Mr.ZJW
     * @Description: 校验签名
     * @param [map]
     * @Date: 2022/5/6 11:11
    **/
    public static Boolean checkSign(Map<String,Object> map){
        String sign = (String) map.get("sign");
        map.remove("sign");
        //生产Sign
        String signGenera = generatorSign(map);
        //校验Sign
        if (signGenera.equals(sign)){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("username","admin");
        map.put("password", "123456");
        map.put("Code", "p4ym");
        String s = generatorSign(map);
        System.out.println("s = " + s);
    }
}
